package tt.dz.egobus.servicemanager.core.resovler;

import org.apache.commons.lang3.StringUtils;

/**
 * @author Anson
 * @date 17-3-16
 * @name 参数转换工具类
 * @since 1.0.1
 */
public final class ClassReflactParamConvert implements ParamConvert<ClassReflactParamConvert.ConvertEntity> {

    private static final String TYPE_SPLIT = "@";

    @Override
    public ConvertEntity convert(String source, String value) {
        ConvertEntity entity = new ConvertEntity("string", source, value);
        if (StringUtils.isEmpty(source) || source.indexOf(TYPE_SPLIT) == -1) {
            return entity;
        }

        String[] requestParamKeies = source.split(TYPE_SPLIT);
        if (requestParamKeies.length != 2) {
            return entity;
        }
        Object obj = this.convertClassOp(requestParamKeies[0], value);
        entity = new ConvertEntity(requestParamKeies[0], requestParamKeies[1], obj);
        return entity;
    }

    private Object convertClassOp(String type, String value) {
        type = type.trim().toUpperCase();
        ClassPrototypeEnum classototypeEnum = ClassPrototypeEnum.valueOf(type);
        if (classototypeEnum == null) {
            return value;
        }
        try {
            Object object = classototypeEnum.convert(value);
            return object;
        } catch (RuntimeException e) {
            return null;
        }
    }

    public class ConvertEntity {

        private String type;
        private String opKey;
        private Object value;

        public ConvertEntity(String type, String opKey, Object value) {
            this.type = type;
            this.opKey = opKey;
            this.value = value;
        }

        public ConvertEntity() {
        }

        public void setType(String type) {
            this.type = type;
        }

        public void setOpKey(String opKey) {
            this.opKey = opKey;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public String getType() {
            return type;
        }

        public String getOpKey() {
            return opKey;
        }

        public Object getValue() {
            return value;
        }
    }
}
